package com.eascs.overdue.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.Format;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eascs.admin.o2o.backfee.controller.O2oComBackFeeController;
import com.eascs.admin.o2o.backfee.entity.FormBackFeeEntity;
import com.eascs.app.dao.PageResult;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.notice.controller.NoticeBaseMasterController;
import com.eascs.overdue.entity.O2oOverdueFormEntity;
import com.eascs.overdue.service.O2oOverdueService;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.tag.MenuTag;

@Controller
@RequestMapping("/overdue")
public class O2oOverdueController extends NoticeBaseMasterController {

	@Autowired
	O2oOverdueService o2oOverdueService;

	@Value("${report.url}")
	private String reportUrl;

	@Value("${report.downExcel.url}")
	private String downExcelUrl;

	@SuppressWarnings("unused")
	@RequestMapping("/index")
	public String index(O2oOverdueFormEntity entity) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "overdueList");
		entity.setPageSize(10);
		PageResult<Object[]> pageResult = o2oOverdueService.getPageO2oOverdueNew(entity);
		String[] oatitles = { "贷款单号", "省区", "经营单位", "借款人姓名", "证件号码", "放款银行", "申请金额(元)", "放款日", "到期日", "拖欠总额(元)", "逾期本金(元)", "逾期利息(元)", "罚息合计(元)", "处置金额(元)", "当前处置状态", "处置时间" ,"统计时间"};
		SelectDataOption[] selectDataOptions = { null, new SelectDataOption("PROVINCE"), null, null, null, new SelectDataOption("BANKTYPEO2O"), null, null, null, null, null, null, null, null, new SelectDataOption("O2O_OVERDUE_STATUS"), null, null,null };
		//String[] oatitles = { "贷款编号", "省区", "经营单位", "借款人姓名", "证件号码", "放款银行", "申请金额(元)", "放款日", "到期日", "拖欠总额(元)", "当前处置状态", "统计时间" };
		//SelectDataOption[] selectDataOptions = { null, new SelectDataOption("PROVINCE"), null, null, null, new SelectDataOption("BANKTYPEO2O"), null, null, null, null, new SelectDataOption("O2O_OVERDUE_STATUS"), null };
		String oapageUrl = "/overdue/index";
		String reporto2ourl = "/overdue/download";
		if (entity != null) {
			String billCode = entity.getBillCode() == null ? "" : entity.getBillCode();
			String loanName = entity.getLoanName() == null ? "" : entity.getLoanName();
			String bankFun = entity.getBankFun() == null ? "" : entity.getBankFun();
			String province = entity.getProvince() == null ? "" : entity.getProvince();
			String status = entity.getStatus() == null ? "" : entity.getStatus();
			String regionalName = entity.getRegionalName() == null ? "" : entity.getRegionalName();
			oapageUrl = UrlUtil.appendUrl(oapageUrl.toString(), "billCode", billCode);
			oapageUrl = UrlUtil.appendUrl(oapageUrl, "loanName", loanName);
			oapageUrl = UrlUtil.appendUrl(oapageUrl, "bankFun", bankFun);
			oapageUrl = UrlUtil.appendUrl(oapageUrl, "province", province);
			oapageUrl = UrlUtil.appendUrl(oapageUrl, "status", status);
			oapageUrl = UrlUtil.appendUrl(oapageUrl, "regionalName", regionalName);
			
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl.toString(), "billCode", billCode);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "loanName", loanName);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "bankFun", bankFun);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "province", province);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "status", status);
			reporto2ourl = UrlUtil.appendUrl(reporto2ourl, "regionalName", regionalName);
			oapageUrl = oapageUrl + "&pageIndex=";
		} else {
			oapageUrl = oapageUrl + "?pageIndex=";
		}
		Button[] titleButton = new Button[] { ButtonHelper.createRedirectButton(null, "/detail?loanapplyNo=") };
		
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, oatitles, oapageUrl);
		//paginationInfo.setTitleButtons(titleButton);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		//paginationInfo.setFormats(new Format[] { null, null, null, null, null, null, new DecimalFormat(",##0.00"), null, null, new DecimalFormat(",##0.00"),null,null });
		paginationInfo.setFormats(new Format[] { null, null, null, null, null, null, new DecimalFormat(",##0.00"), null, null, new DecimalFormat(",##0.00"),new DecimalFormat(",##0.00"),new DecimalFormat(",##0.00"),new DecimalFormat(",##0.00"),new DecimalFormat(",##0.00"),null,null,null});
		ViewContext.put("vo", entity);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("reporto2ourl", reporto2ourl);
		return "overdue/index";
	}
	
	@RequestMapping("/download")
	public void dowanload(O2oOverdueFormEntity entity,HttpServletResponse httpServletResponse, HttpServletRequest request) {
		entity.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult = o2oOverdueService.findByPageReportList(entity);
		String path = O2oComBackFeeController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/overdue-model.xls").toString();
		OutputStream os = null;
		try {
			String outfile = "逾期列表.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), O2oComBackFeeController.class.getResourceAsStream("/excelTemplate/overdue-model.xls"), defaultRowWriteHandler);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}
	
}
